package com.muqi.app.qlearn.student;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.io.Serializable;
import java.util.List;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;

import com.muqi.app.project.contants.MContants;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;
import com.muqi.app.user.widget.ChildrenWindow;
import com.muqi.app.user.widget.ClassWithStudentsWindow;

public abstract class BaseStudentActivity extends BaseFragmentActivity
		implements ChildrenWindow.ChildrenListener {
	protected CupboardSQLiteOpenHelper dbHelper;
	protected SQLiteDatabase sqlDb;
	protected List<ChildBean> myChildren;
	private ChildrenWindow childWindow = null;
	protected String currentChildName = "";
	protected ChildBean currentChild;

	@Override
	protected void onInit() {
		dbHelper = new CupboardSQLiteOpenHelper(this);
		sqlDb = dbHelper.getWritableDatabase();
		myChildren = cupboard().withDatabase(sqlDb).query(ChildBean.class)
				.list();

		if (myChildren != null && myChildren.size() > 0) {
			if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {// 只有以家长身份登录时，才有此切换功能
				childWindow = new ChildrenWindow(this, this, myChildren);
			}

			for (ChildBean child : myChildren) {
				if (child.child_id.equals(mSpUtil.getCurrentChildId())) {
					currentChildName = child.name;
					currentChild = child;
					break;
				}
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		myChildren = cupboard().withDatabase(sqlDb).query(ChildBean.class)
				.list();
	}

	@Override
	protected void onData() {
		// TODO Auto-generated method stub
	}

	public void showChildrenWindow(View v) {
		if (childWindow != null) {
			childWindow.showPopupWindow(v, mSpUtil.getCurrentChildId());
		}
	}

	protected abstract void onChoiceChildResult(ChildBean myChild);

	@Override
	public void onSeleectChild(ChildBean child) {
		if (child.child_id.equals(mSpUtil.getCurrentChildId())) {
			return;
		}
		mSpUtil.setCurrentChildId(child.child_id);
		mSpUtil.setChildClassId(child.class_id);
		mSpUtil.setChildGradeId(child.grade_id);
		mSpUtil.setChildSchoolId(child.school_id);
		mSpUtil.setChildName(child.name);
		mSpUtil.setClassName(child.class_name);
		mSpUtil.setSchoolName(child.school_name);
		mSpUtil.setCurrentIm(child.im_user_id);
		mSpUtil.setCurrentAva(child.avatar_02);
		currentChildName = child.name;

		onChoiceChildResult(child);
		Intent intent = new Intent();
		intent.setAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		intent.putExtra(MContants.CHANGE_CURRENT_CHILD_DATAS,
				(Serializable) child);
		sendBroadcast(intent);
	}
}
